package hot100.链表.不需要虚拟头;

import hot100.链表.ListNode;

/**
 *
 */
public class huiwenChain234 {
    public boolean isPalindrome(ListNode head) {
        if (head == null || head.next == null) { return true;}

        ListNode middle = getMiddle(head);
        ListNode reverse = reverse(middle);
        while (reverse != null) {
            if (head.val != reverse.val) {
                return false;
            }
            reverse = reverse.next; head = head.next;
        }
        return true;
    }

        // Get MiddleNode
        private ListNode getMiddle(ListNode head) {
            ListNode middle=head, guide=head;
            /**
             * 思考 1所要的元素点 2奇偶结尾情况
             *  odd: 0 1[2] 34  guide步数 -1= middle步数 ==2 (guide.next!=null拦截一步)
             * even: 0 1[2] 3  guide步数 = middle步数 ==2
             * 可以理解为 奇数情况会多走一步 需要拿条件拦截一下
             * **/
            while (guide != null && guide.next != null) {
                guide = guide.next.next;
                middle = middle.next;
            }
            return guide != null ? middle.next : middle;
        }

        private ListNode reverse(ListNode head) {
            ListNode left=null, right=head;
            while (right != null) {
                ListNode temp = right.next;
                right.next = left;
                left = right;
                right = temp;
            }
            return left;
        }


    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        head.next = new ListNode(2);
        head.next.next = new ListNode(2);
        head.next.next.next = new ListNode(1);

        huiwenChain234 a = new huiwenChain234();
        System.out.println(a.isPalindrome(head));
    }
}